package com.topcent.tioxyc.xxljob;

/**
 * @author: 陈百万
 * @date: 2025/4/11 14:49
 * @Description: 备选类
 */
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.DeliveryDocumentsMapper;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.DeliveryDocuments;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.pojo.YY1_KPI;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class YY1_KPI101 {

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @Autowired
    private DeliveryDocumentsMapper deliveryDocumentsMapper;

    //@XxlJob("YY1_KPI")
    public void YY_KPl() {
        List<YY1_KPI> yy1KpiList = fetchKpiData();
        if (!yy1KpiList.isEmpty()) {
            yy1KpiMapper.truncateTable();
            //yy1KpiMapper.insertBatch(yy1KpiList);
        }

        List<DeliveryDocuments> deliveryList = fetchDeliveryData();
        if (!deliveryList.isEmpty()) {
            deliveryDocumentsMapper.truncateTable();
            //deliveryDocumentsMapper.insertBatch(deliveryList);
        }
    }

    private List<YY1_KPI> fetchKpiData() {
        List<YY1_KPI> list = new ArrayList<>();
        Header[] headers = buildHeaders();
        JSONObject response = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_SALESBOARD_CDS/YY1_SalesBoard", headers, null);
        JSONArray jsonArray = JSONUtil.parseArray(JSONUtil.parseObj(response.getStr("d")).getStr("results"));
        for (Object obj : jsonArray) {
            YY1_KPI kpi = JSONUtil.toBean((JSONObject) obj, YY1_KPI.class);
            kpi.setYY1_lachangedatetime1_SDHs(parseSapDate(kpi.getYY1_lachangedatetime1_SDH()));
            kpi.setCreationDates(parseSapDate(kpi.getCreationDate()));
            kpi.setYY1_lastapptime_SDHS(parseSapDate(kpi.getYY1_lastapptime_SDH()));
            kpi.setRequestedDeliveryDates(parseSapDate(kpi.getRequestedDeliveryDate()));

            String businessText = kpi.getBusinessPartnerGroupingText();
            if (StringUtils.isNotBlank(businessText) && businessText.contains("-")) {
                kpi.setBusinessPartnerGroupingText(businessText.substring(0, businessText.indexOf("-")));
            }

            if (StringUtils.isNotBlank(kpi.getVCDescription()) && kpi.getVCDescription().contains("标准码:")) {
                int startIdx = kpi.getVCDescription().indexOf("标准码:") + 4;
                int endIdx = kpi.getVCDescription().indexOf(";", startIdx);
                kpi.setYY1_KS_SD_SDI(kpi.getVCDescription().substring(startIdx, endIdx));
            }

            kpi.setGsjing(kpi.getNetAmount_1().multiply(kpi.getExchangeRate_b()));
            kpi.setGshan(kpi.getConditionAmount1().multiply(kpi.getExchangeRate_b()));
            list.add(kpi);
        }
        return list;
    }

    private List<DeliveryDocuments> fetchDeliveryData() {
        List<DeliveryDocuments> list = new ArrayList<>();
        Header[] headers = buildHeaders();
        JSONObject response = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_DELIVERYDOCUMENT_API_CDS/YY1_DeliveryDocument_API", headers, null);
        JSONArray jsonArray = JSONUtil.parseArray(JSONUtil.parseObj(response.getStr("d")).getStr("results"));
        for (Object obj : jsonArray) {
            DeliveryDocuments doc = JSONUtil.toBean((JSONObject) obj, DeliveryDocuments.class);
            doc.setCreationDates(parseSapDate(doc.getCreationDate()));
            doc.setDocumentDates(parseSapDate(doc.getDocumentDate()));
            doc.setActualGoodsMovementDates(parseSapDate(doc.getActualGoodsMovementDate()));
            doc.setPlannedGoodsIssueDates(parseSapDate(doc.getPlannedGoodsIssueDate()));
            doc.setCreationDate_1s(parseSapDate(doc.getCreationDate_1()));

            switch (doc.getBusinessPartnerGrouping()) {
                case "BPAB": doc.setBusinessPartnerGrouping("法人供应商"); break;
                case "Z001": doc.setBusinessPartnerGrouping("外部供应商"); break;
                case "Z002": doc.setBusinessPartnerGrouping("贸易商"); break;
                case "Z003": doc.setBusinessPartnerGrouping("应用商"); break;
                case "Z004": doc.setBusinessPartnerGrouping("零售商"); break;
                case "Z005": doc.setBusinessPartnerGrouping("员工供应商"); break;
                case "Z006": doc.setBusinessPartnerGrouping("财务供应商"); break;
                default: doc.setBusinessPartnerGrouping("未知分组");
            }

            list.add(doc);
        }
        return list;
    }

    private Header[] buildHeaders() {
        return new Header[]{
                new BasicHeader("Accept", "application/json"),
                new BasicHeader("Authorization", "Basic " + KeyConstant.SAP01),
                new BasicHeader("x-csrf-token", "Fetch")
        };
    }

    private DateTime parseSapDate(String sapDateStr) {
        if (StringUtils.isNotBlank(sapDateStr)) {
            long timestamp = Long.parseLong(ConnmeUtils.extractTimestamp(sapDateStr));
            LocalDateTime ldt = ConnmeUtils.convertTimestampToLocalDateTime(timestamp);
            return new DateTime(ConnmeUtils.formatDateTime(ldt), DatePattern.NORM_DATETIME_FORMAT);
        }
        return null;
    }
}
